<?php
class AuthenticateController extends ControllerBase {

	public function init(){
		Util::app()->theme 	= SITE_THEME;
		$this->layout 		= '//layouts/none';
		parent::init();
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=>Util::getRegister(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/*
	 * actionPassword
	 */
    public function actionPassword() {
    	$model = new UserChangePassword;
		if(isset($_POST['UserChangePassword'])) {
			$model->attributes	= $_POST['UserChangePassword'];
			if($model->validate()) {
				$objAccount 					= User::model()->recover()->findbyPk(Yii::app()->user->id);
				$objAccount->password 			= UserModule::encrypting($model->password);
				$objAccount->recover_password 	= null;
				$objAccount->activkey			= UserModule::encrypting(microtime().$model->password);
				$objAccount->save();
				$this->redirect(array("/user/logout"));
			}
		}
		$this->render('password',compact('model'));
    }

	/*
	 * actionAvatar
	 */
    public function actionAvatar() {
    	if (User::model()->checkActiveFirstLogin()) {
			$this->redirect(array('/authenticate/password'));
		}

		$userId		= Yii::app()->user->id;
		$member		= Member::model()->findByPk($userId);
		
		// Get old avatar
		$oldAvatar	= $member->avatar;
		
		if(isset($_POST['Member'])) {
			// Get data post
			$member->attributes		= $_POST['Member'];
			$member->user_id		= $userId;
			$validMember 			= $member->validate();

			if ($validMember) {
				// Update profile
				if (isset($_FILES['Member']['size']['avatar']) && $_FILES['Member']['size']['avatar'] > 0) {
					$avatar 			= CUploadedFile::getInstance($member, 'avatar');
					$tmpNm				= time()-1;
	                $imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
	                $member->avatar		= $imageName;
	                $avatar->saveAs(Util::pathUpload('profile') .'/' . $imageName);
	
					if (($oldAvatar != '') && file_exists(Util::pathUpload('profile') .'/' . $oldAvatar)) {
	               		unlink(Util::pathUpload('profile') .'/' . $oldAvatar);
	                }
	                $member->save();
	                $this->redirect(array('/authenticate/profile'));
				}
				//else {
				//	$member->avatar 	= $oldAvatar;
				//}
			}
			else {
				$member->avatar = "";
			}
			
			/*if($model->validate()) {
				$objAccount 					= User::model()->recover()->findbyPk(Yii::app()->user->id);
				$objAccount->password 			= UserModule::encrypting($model->password);
				$objAccount->recover_password 	= null;
				$objAccount->activkey			= UserModule::encrypting(microtime().$model->password);
				$objAccount->save();
				$this->redirect(array("/user/logout"));
			}*/
		}
		$this->render('avatar',compact('member'));
    }
    
	/**
	 * Updates a particular model.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionProfile() {
		if (User::model()->checkActiveFirstLogin()) {
			$this->redirect(array('/authenticate/password'));
		}

		$userId		= Yii::app()->user->id;
		$member		= Member::model()->findByPk($userId);
		if ($member->avatar == "") {
			$this->redirect(array('/authenticate/avatar'));
		}
		
		$account	= $member->account;
		$membercode	= MemberCode::model()->getCode($account->id);
		$education	= Education::model()->getEducation($membercode->code);
		list($semesters, $subjects) = Util::getSemesterInfo($education);
		$semester_delete = $subject_delete = null;

		// Get old avatar
		$oldAvatar	= $member->avatar;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($member);
		if(isset($_POST['Member'])) {
			// Get data post
			$member->attributes		= $_POST['Member'];
			$education->attributes	= $_POST['Education'];
			if (isset($_POST['Semester'])) {
				$semesters 				= $_POST['Semester'];
				$subjects 				= $_POST['Subject'];
				$subject_delete			= $_POST['subject_id_delete'];
				$semester_delete		= $_POST['semester_id_delete'];
			}

			// Connvert string to lowercase
			$member->fullname		= Util::formatFullName($member->fullname, true);
			// Clear all character non numberic
			$inputPhone				= $member->phone;
			$inputCellPhone			= $member->cellphone;
			$member->phone			= Util::formatPhone($inputPhone, false);
			$member->cellphone		= Util::formatPhone($inputCellPhone, false);

			$validMember 		= $member->validate();
			$validEducation 	= $education->validate();

			if($validMember && $validEducation) {
				// Update account
				$account->email	= $member->email;
				$account->save();

				// Update profile
				/*if (isset($_FILES['Member']['size']['avatar']) && $_FILES['Member']['size']['avatar'] > 0) {
					$avatar 			= CUploadedFile::getInstance($member, 'avatar');
					$tmpNm				= time()-1;
                	$imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
                	$member->avatar		= $imageName;
                	$avatar->saveAs(Util::pathUpload('profile') .'/' . $imageName);

					if (($oldAvatar != '') && file_exists(Util::pathUpload('profile') .'/' . $oldAvatar)) {
                		unlink(Util::pathUpload('profile') .'/' . $oldAvatar);
                	}
				}
				else {
					$member->avatar 	= $oldAvatar;
				}*/
				$member->save();

				//Create education
				$education->save();

				// Update semester and subject
				if (isset($semesters)) {
					foreach ($semesters as $index => $semester) {
						if (isset($semester['id'])) {
							$semesterModel	= Semester::model()->findByPk($semester['id']);
						}
						else {
							$semesterModel	= new Semester();
						}

						$semesterModel->attributes 		= $semester;
						$semesterModel->education_id	= $education->id;
						$semesterModel->save();

						// Update subject
						foreach ($subjects[$index] as $subject) {
							if (isset($subject['id'])) {
								$subjectModel	= Subject::model()->findByPk($subject['id']);
							}
							else {
								$subjectModel	= new Subject();
							}

							$subjectModel->attributes 		= $subject;
							$subjectModel->semester_id		= $semesterModel->id;
							$subjectModel->save();
						}
					}
				}

				// Delete subject
				if ($subject_delete != '') {
					$listSubjectDelete = explode(',' , $subject_delete);
					Subject::model()->deleteByPk($listSubjectDelete);
				}

				// Delete semester
				if ($semester_delete != '') {
					$listSemesterDelete = explode(',' , $semester_delete);
					Semester::model()->deleteByPk($listSemesterDelete);
				}

				// Active member
				$account->updateByPk($userId, array('superuser' => MEMBER));

				// Redirect to view
				$this->redirect(array('site/index'));
			}
			$member->phone		= $inputPhone;
			$member->cellphone	= $inputCellPhone;
		}

		$paramSemesterForm = array('semesters' => $semesters, 'subjects' => $subjects, 'subject_delete' => $subject_delete, 'semester_delete' => $semester_delete);
		$this->render('profile', compact('member', 'account', 'education', 'membercode', 'paramSemesterForm'));
	}
}